package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.BspsLoginTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.model.UserSessionInfo;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.UserBindRelationQueryRequest;
import cc.rengu.igas.bsps.facade.response.UserBindRelationQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.enums.PinTypeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.PasswordInfo;
import cc.rengu.oltp.service.realize.SafeKeyBoardService;
import cc.rengu.oltp.service.realize.impl.SafeKeyBoardServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 用户绑定关系查询服务
 *
 * @author zhangxuran （联调修改）
 * @version 1.0
 * @date 2020.04.13
 */
public class UserBindRelationQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        UserBindRelationQueryRequest userBindRelationQueryRequest = new UserBindRelationQueryRequest();
        ConvertUtil.convertOutput(userBindRelationQueryRequest);
        return userBindRelationQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        UserBindRelationQueryRequest userBindRelationQueryRequest = (UserBindRelationQueryRequest) request;
        String instId = userBindRelationQueryRequest.getHeader().getInstId();
        String userSessionId = userBindRelationQueryRequest.getHeader().getSession();
        String openId = userBindRelationQueryRequest.getOpenId();
        String userLoginId = userBindRelationQueryRequest.getUserId();
        String loginType = userBindRelationQueryRequest.getLoginType();
        String password = userBindRelationQueryRequest.getPassword();
        rglog.info("必填性校验");
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(loginType)) {
            rglog.error("参数必填性校验失败！instId:<{}>,loginType:<{}>", instId, loginType);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        UserInfo userInfo;
        BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
        if (BspsLoginTypeEnum.OPEN_ID.getLoginType().equals(loginType)) {
            rglog.info("公众号登录");
            if (StringUtil.isEmptyOrNull(openId)) {
                rglog.error("参数必填性校验失败！instId:<{}>,openId:<{}>", instId, openId);
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            userInfo = bspsUserInfoMapper.selectBspsUserInfoByOpenId(instId, openId);
            if (null == userInfo) {
                rglog.error("用户查询为空！instId:<{}>,openId:<{}>", instId, openId);
                throw new BizException("", "用户绑定关系信息查询失败");
            }
        } else if (BspsLoginTypeEnum.ACCT_PASSWORD.getLoginType().equals(loginType)) {
            rglog.info("账号密码登录");
            if (StringUtil.isEmptyOrNull(userLoginId) || StringUtil.isEmptyOrNull(password)) {
                rglog.error("参数必填性校验失败！userLoginId:<{}>,password:<{}>", userLoginId, password);
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
            userInfo = bspsUserInfoMapper.selectBspsUserInfoByUserLoginId(instId, userLoginId);
            if (null == userInfo) {
                rglog.error("用户查询为空！instId:<{}>,userLoginId:<{}>", instId, userLoginId);
                throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
            }
            rglog.info("校验密码开始");
            SafeKeyBoardService safeKeyBoardService = new SafeKeyBoardServiceImpl();
            //校验用户登录密码
            boolean passwordFlag = false;
            BspsMchntBindInfoMapper mchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
            List<MchntBindInfo> mchntBindlist = mchntBindInfoMapper.selectBspsMchntBindInfoListByUserId(instId, userInfo.getUserId());
            for (MchntBindInfo mchntBindInfo : mchntBindlist) {
                PasswordInfo passwordInfo = new PasswordInfo(mchntBindInfo.getMchntNo(), PinTypeEnum.MIXED, password);
                password = safeKeyBoardService.encryptPassword(instId, null, passwordInfo, null);
                if (userInfo.getLoginPassword().equalsIgnoreCase(password)) {
                    rglog.info("密码校验成功！instId:<{}>,mchntNo:<{}>", instId, mchntBindInfo.getMchntNo());
                    passwordFlag = true;
                    rglog.info("校验密码成功");
                    break;
                }
            }
            rglog.info("校验密码结束");
            if (!passwordFlag) {
                throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
            }
            UserSessionInfo keySessionInfo = JSON.parseObject(RedisUtil.onceGet(userSessionId), UserSessionInfo.class);
            keySessionInfo.setPasswordVerifyKey(userBindRelationQueryRequest.getPassword());
            RedisUtil.onceSet(userSessionId, JSONObject.toJSONString(keySessionInfo), BspsAppParamConstant.SESSION_EFFECTIVE_TIME);
            rglog.info("session中存放密码校验成功标识");
        } else {
            rglog.error("传入参数用户登录类型异常！instId:<{}>,loginType:<{}>", instId, loginType);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        BizResponse<UserBindRelationQueryResponse> bizResponse = new BizResponse<>();
        UserBindRelationQueryResponse userBindRelationQueryResponse = new UserBindRelationQueryResponse();
        userBindRelationQueryResponse.setOpenId(userInfo.getOpenId());
        userBindRelationQueryResponse.setUserLoginId(userInfo.getUserLoginId());
        userBindRelationQueryResponse.setUserMobileId(userInfo.getUserMobileId());
        userBindRelationQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        userBindRelationQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(userBindRelationQueryResponse.getRespCode());
        bizResponse.setRespDesc(userBindRelationQueryResponse.getRespDesc());
        bizResponse.setResult(userBindRelationQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        UserBindRelationQueryResponse userBindRelationQueryResponse = (UserBindRelationQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(userBindRelationQueryResponse);
    }

}
